package com.oriental.manage.core.bigDataDownloadThread;

import com.oriental.manage.core.bigDataDownloadThread.base.BaseDownloadThread;
import com.oriental.manage.core.fileUtils.ExcelContentExt;
import com.oriental.manage.core.fileUtils.ExtExcelWriterCallBack;
import com.oriental.manage.core.fileUtils.HeaderExt;
import com.oriental.manage.core.utils.ApplicationContextUtil;
import com.oriental.manage.core.utils.Bean2MapUtil;
import com.oriental.manage.core.utils.DateUtils;
import com.oriental.manage.core.utils.SessionUtils;
import com.oriental.paycenter.commons.mode.Response;
import com.oriental.settlementfront.service.facade.common.model.Pagination;
import com.oriental.settlementfront.service.facade.manager.MchntTransDetailFacade;
import com.oriental.settlementfront.service.facade.manager.model.MchntTransDetailDTO;
import org.apache.commons.lang3.StringUtils;
import org.webbuilder.office.excel.api.poi.POIExcelApi;
import org.webbuilder.office.excel.config.CustomCellStyle;
import org.webbuilder.office.excel.config.ExcelWriterConfig;
import org.webbuilder.office.excel.config.Header;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by luoxin on 2017/2/28.
 */
public class DownloadMchntTransThread extends BaseDownloadThread<MchntTransDetailDTO> {
    private MchntTransDetailFacade mchntTransDetailFacade = ApplicationContextUtil.getBean(MchntTransDetailFacade.class);

    public DownloadMchntTransThread(MchntTransDetailDTO mchntTransDetailDTO) {
        this.queryModel = mchntTransDetailDTO;
    }

    @Override
    protected void config(LinkedList<Header> tHeaders) {
        //设置输出文件
        setFileNameOut("MCHNT_TRANS-" + DateUtils.now() + "-.zip");

        tHeaders.add(new HeaderExt("序号", "index"));
        tHeaders.add(new HeaderExt("商户", "mchntCode", ExcelContentExt.MCHNT));
        tHeaders.add(new HeaderExt("发起方", "initiatorCode", ExcelContentExt.MCHNT));
        tHeaders.add(new HeaderExt("订单号", "orderNo"));
        tHeaders.add(new HeaderExt("订单时间", "orderTime"));
        tHeaders.add(new HeaderExt("订单金额(元)", "orderAmt", ExcelContentExt.CURRENCY));
        tHeaders.add(new HeaderExt("接入渠道", "connChannelDesc"));
        tHeaders.add(new HeaderExt("交易类型", "transCodeDesc"));
        tHeaders.add(new HeaderExt("交易状态", "transStatusDesc"));
        tHeaders.add(new HeaderExt("交易金额(元)", "transAmt", ExcelContentExt.CURRENCY));
        tHeaders.add(new HeaderExt("业务请求流水号", "busiReqNo"));
        tHeaders.add(new HeaderExt("业务请求时间", "busiReqTime"));
        tHeaders.add(new HeaderExt("勾兑状态", "chkStatusDesc"));
        tHeaders.add(new HeaderExt("业务清算日期", "busiSettleDate"));
        tHeaders.add(new HeaderExt("交易确认日期", "transConfirmDate"));
        tHeaders.add(new HeaderExt("是否参与清算", "settleFlag"));
        tHeaders.add(new HeaderExt("清算状态", "settleStatusDesc"));
        tHeaders.add(new HeaderExt("支付订单号", "innerPayTransNo"));
        tHeaders.add(new HeaderExt("是否已删除", "flag"));
    }

    protected void calculatePageCount() {
        if (rowCount % pageSize != 0) {
            pageCount = 1 + (rowCount / (pageSize * 2));
        } else {
            pageCount = rowCount / (pageSize * 2);
        }
    }

    @Override
    protected File buildTempFile(int pageNum) throws Exception {
        List<Object> datas = new ArrayList<>();
        File tempFile = null;

        int num = 0;
        Response<Pagination<MchntTransDetailDTO>> response;
        do {
            queryModel.setStartRow(((pageNum - 1) * 2 + num) * this.pageSize);
            response = mchntTransDetailFacade.pageQuery(queryModel, SessionUtils.getUserName());
            int i = 1;
            for (MchntTransDetailDTO mchntTransDetailDTO : response.getResult().getPageList()) {
                Map map = Bean2MapUtil.convertBean(mchntTransDetailDTO);
                if ("1".equals(mchntTransDetailDTO.getDeleteFlag())) {
                    map.put("flag", "删除");
                }
                if ("0".equals(mchntTransDetailDTO.getDeleteFlag())) {
                    map.put("flag", "正常");
                }
                if ("0".equals(mchntTransDetailDTO.getSettleFlag())) {
                    map.put("settleFlag", "无需清分");
                }
                if ("1".equals(mchntTransDetailDTO.getSettleFlag())) {
                    map.put("settleFlag", "参与清分");
                }
                if ("2".equals(mchntTransDetailDTO.getSettleFlag())) {
                    map.put("settleFlag", "止付");
                }
                if ("3".equals(mchntTransDetailDTO.getSettleFlag())) {
                    map.put("settleFlag", "冻结");
                }
                map.put("index", this.queryModel.getStartRow() + i);
                datas.add(map);
                i++;

                if (i % 1000 == 0) {
                    Thread.sleep(1000);
                }
            }

            num++;
        } while (num < 2 && response.getResult().getPageList().size() > 0);

        ExcelWriterConfig config = new ExcelWriterConfig() {
            @Override
            public CustomCellStyle getCellStyle(int row, int column, String header, Object value) {
                CustomCellStyle style = super.getCellStyle(row, column, header, value);
                if (row > 0 && StringUtils.equals("orderTime", header)) {
                    style.setFormat("yyyy-m-d h:mm:ss");
                }
                if (row > 0 && StringUtils.equals("busiReqTime", header)) {
                    style.setFormat("yyyy-m-d h:mm:ss");
                }
                return style;
            }
        };
        Map m = response.getResult().getSumData();
        m.put("initiatorCode", "总笔数:");
        m.put("orderNo", this.rowCount);
        m.put("orderTime", "总计:");
        StringBuilder sb = new StringBuilder();
        sb.append("商户交易查询：第")
                .append(pageNum)
                .append("张表")
                .append(DateUtils.now())
                .append(".xlsx");
        tempFile = fileDownAjax.touch(sb.toString());
        datas.add(m);
        config.setHeaders(tHeaders);
        config.setDatas(datas);
        config.setSheetName("商户交易查询：第" + pageNum + "张表");
        ExtExcelWriterCallBack ca = new ExtExcelWriterCallBack(config);
        FileOutputStream outputStream = new FileOutputStream(tempFile);
        POIExcelApi.getInstance().write(outputStream, ca);
        return tempFile;
    }


    @Override
    protected void queryRowCount() {
        Response<Pagination<MchntTransDetailDTO>> response
                = mchntTransDetailFacade.pageQuery(queryModel, SessionUtils.getUserName());
        if (response != null) {
            this.rowCount = (int) response.getResult().getTotalCount();
        }
    }
}
